﻿using System;
using System.Globalization;
using System.Windows.Forms;
using SGLLv2.UI.Properties;

namespace SGLLv2.UI
{
    public partial class FormComplaints : Template.FormTemplate, IMethods
    {
        // Declare Global Variables
private MDIParent mdiParent;
        private long? _complaintID;

        // Class Constructor
        public FormComplaints()
        {
            InitializeComponent();
        }

        // Form
        private void FormComplaints_Load(object sender, EventArgs e)
        {
            // Declare Local Variables
            mdiParent = (MDIParent)(ParentForm);
            if (mdiParent == null) return;

            try
            {
                // Fill out each dataset.
                sP_USERS_SELECT_SPECIALTableAdapter.Fill(dataSetSGLL.SP_USERS_SELECT_SPECIAL);
                sP_ROUTES_SELECTTableAdapter.Fill(dataSetSGLL.SP_ROUTES_SELECT);
                tYPES_OF_SAMPLESTableAdapter.Fill(dataSetSGLL.TYPES_OF_SAMPLES);
                sP_DOCTORS_SELECTTableAdapter.Fill(dataSetSGLL.SP_DOCTORS_SELECT);
                sP_USERS_SELECTTableAdapter.Fill(dataSetSGLL.SP_USERS_SELECT);

                // Removed preselected Filter ComboBoxes.
                comboBoxDoctorFilter.SelectedIndex = -1;
                comboBoxCloseByUserFilter.SelectedIndex = -1;
                comboBoxTypeOfSampleFilter.SelectedIndex = -1;
                comboBoxDepartamentFilter.SelectedIndex = -1;
                comboBoxRouteFilter.SelectedIndex = -1;

                // Set maximum date for date time pickers
                dateTimePickerFilterStart.MaxDate = dateTimePickerFilterEnd.MaxDate = dateTimePickerDate.MaxDate = DateTime.Today;

                // Clear form
                ClearForm();

                // Show complaints
                RefreshComplaints();

                // Prevent from calling future times the Complaint Form
                mdiParent.toolStripMenuItemComplaints.Enabled = mdiParent.toolStripButtonComplaints.Enabled = false;

                // Hooking Up Events
                dateTimePickerFilterStart.ValueChanged += dateTimePickerFilterStart_ValueChanged;
                dateTimePickerFilterEnd.ValueChanged += dateTimePickerFilterEnd_ValueChanged;
            }
            catch (Exception exception)
            {
                // Report Error
                mdiParent.SetMessage(MDIParent.MessageType.Error, exception.Message);
                Utilities.ExceptionManager(exception);
            }
        }

        // Text Boxes
        private void textBoxComments_KeyDown(object sender, KeyEventArgs e)
        {
            // Validate if is F5 Key.
            if (!e.KeyCode.Equals(Keys.F5)) return;

            // Add date time to the comment textbox.
            if ((textBoxComments.Text.Length + DateTime.Now.ToString(CultureInfo.InvariantCulture).Length) >= textBoxComments.MaxLength) return;
            textBoxComments.Text += string.Concat(DateTime.Now, " ");
            textBoxComments.SelectionStart = textBoxComments.Text.Length;
        }

        // Combo Boxes
        private void comboBoxForm_SelectionChangeCommitted(object sender, EventArgs e)
        {
            EnableButtonSave();
        }
        private void comboBoxFilters_SelectionChangeCommitted(object sender, EventArgs e)
        {
            RefreshComplaints();
        }
        private void comboBoxForm_KeyDown(object sender, KeyEventArgs e)
        {
            // Validations if is Delete Key.
            if (!e.KeyCode.Equals(Keys.Delete)) return;

            // Declare Local Variable
            ComboBox comboBox = sender as ComboBox;

            // Check is is null.
            if (comboBox != null) comboBox.SelectedIndex = -1;

            // Refresh Save Button Status
            EnableButtonSave();
        }
        private void comboBoxFilter_KeyDown(object sender, KeyEventArgs e)
        {
            // Validations if is Delete Key.
            if (!e.KeyCode.Equals(Keys.Delete)) return;

            // Declare Local Variable
            ComboBox comboBox = sender as ComboBox;

            // Check is is null.
            if (comboBox != null) comboBox.SelectedIndex = -1;

            // Update complaints table
            RefreshComplaints();
        }

        // Buttons
        private void buttonDoctor_Click(object sender, EventArgs e)
        {
            // Show Search Dialog Box
            SearchDialog.SearchDialog searchDialog = new SearchDialog.SearchDialog(dataSetSGLL.SP_DOCTORS_SELECT, Resources.SearchDialogBoxTitleDoctors);
            if (searchDialog.ShowDialog().Equals(DialogResult.Cancel)) return;
            comboBoxDoctor.SelectedValue = searchDialog.SelectedRow.Cells[0].Value.ToString();
            comboBoxDoctor.SelectedText = searchDialog.SelectedRow.Cells[1].Value.ToString();

            // Enable Save Button Function
            EnableButtonSave();
        }
        private void buttonDoctorFilter_Click(object sender, EventArgs e)
        {
            SearchDialog.SearchDialog searchDialog = new SearchDialog.SearchDialog(dataSetSGLL.SP_DOCTORS_SELECT, Resources.SearchDialogBoxTitleDoctors);
            if (searchDialog.ShowDialog().Equals(DialogResult.Cancel)) return;
            comboBoxDoctorFilter.SelectedValue = searchDialog.SelectedRow.Cells[0].Value.ToString();
            comboBoxDoctorFilter.SelectedText = searchDialog.SelectedRow.Cells[1].Value.ToString();

            // Enable Save Button Function
            RefreshComplaints();
        }

        // Date Time Picker
        private void dateTimePickerFilterStart_ValueChanged(object sender, EventArgs e)
        {
            // Avoid overlap in dates.
            dateTimePickerFilterEnd.MinDate = dateTimePickerFilterStart.Value;

            RefreshComplaints();
        }
        private void dateTimePickerFilterEnd_ValueChanged(object sender, EventArgs e)
        {
            // Avoid overlap in dates.
            dateTimePickerFilterStart.MaxDate = dateTimePickerFilterEnd.Value;

            RefreshComplaints();
        }

        // Data Grid View
        private void dataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            dataGridView.ClearSelection();
        }
        private void dataGridView_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            // Validation
            if (dataGridView.CurrentRow == null) return;

            // Initializing ID variable
            _complaintID = Convert.ToInt64(dataGridView[ordenDataGridViewTextBoxColumn.Index, e.RowIndex].Value);
            
            // Coding
            comboBoxOpenByUser.Text = dataGridView[usuarioDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString();
            comboBoxDoctor.SelectedIndex = comboBoxDoctor.FindStringExact(dataGridView[doctorDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString());
            comboBoxTypeOfSample.SelectedIndex = comboBoxTypeOfSample.FindStringExact(dataGridView[muestraDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString());
            comboBoxDepartament.Text = dataGridView[departamentoDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString();
            comboBoxTypeOfComplaint.Text = dataGridView[tipoDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString();
            dateTimePickerDate.Value = Convert.ToDateTime(dataGridView[fechaDataGridViewTextBoxColumn.Index, e.RowIndex].Value);

            textBoxComments.Text = dataGridView[comentariosDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString();
            if (dataGridView[cLOSEBYUSERDataGridViewTextBoxColumn.Index, e.RowIndex].Value == DBNull.Value)
                comboBoxCloseByUser.SelectedIndex = -1;
            else
                comboBoxCloseByUser.Text = dataGridView[cLOSEBYUSERDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString();
            labelUpdated.Text = dataGridView[uPDATEDDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString();
            labelInserted.Text = dataGridView[iNSERTEDDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString();

            // Enable Controls
            EnabledControls(false);
            EnableButtonSave();
        }

        // Interface
        public void New()
        {
            throw new NotImplementedException();
        }
        public void Save()
        {
            try
            {
                // Begin
                mdiParent.Begin();

                var tmpComplaintID = _complaintID;

                // Coding
                mdiParent.toolStripButtonSave.Enabled = false;
                queriesTableAdapter.InsertUpdateComplaints
                (
                    ref _complaintID,
                    Convert.ToByte(comboBoxTypeOfSample.SelectedValue),
                    comboBoxOpenByUser.Text,
                    comboBoxDoctor.SelectedValue.ToString(),
                    dateTimePickerDate.Value,
                    textBoxComments.Text.Trim(),
                    comboBoxDepartament.Text,
                    string.IsNullOrEmpty(comboBoxCloseByUser.Text) ? null : comboBoxCloseByUser.Text,
                    comboBoxTypeOfComplaint.Text
                );

                // Let the user know what's going on.
                mdiParent.SetMessage(MDIParent.MessageType.Successful, tmpComplaintID == null ? string.Format(Resources.MessageSuccessfulInsertCall, _complaintID) : string.Format(Resources.MessageSuccessfulUpdateCall, _complaintID));

                // Update number of complaints.
                mdiParent.UpdateTodayCallsComplaints();

                // Refresh Complaints
                RefreshComplaints();

                // Reselect Row
                if (tmpComplaintID != null)
                {
                    var row = sPCOMPLAINTSSELECTBindingSource.Find(dataSetSGLL.SP_COMPLAINTS_SELECT.OrdenColumn.Caption, _complaintID);
                    dataGridView.BeginInvoke((MethodInvoker)delegate
                    {
                        dataGridView.Rows[row].Selected = true;
                    });
                }

                // Clear form
                ClearForm();

                // Log File
            }
            catch (Exception exception)
            {
                // Report Error
                Utilities.ExceptionManager(exception);
            }
            finally
            {
                // End
                mdiParent.End();
            }
        }
        public void Print()
        {
            // Prevent future invocations to the print button.
            mdiParent.toolStripMenuItemPrint.Enabled = mdiParent.toolStripButtonPrint.Enabled = false;

            // Call preview form
            FormPrintPreview formPrintPreview = new FormPrintPreview(this, dataSetSGLL.SP_COMPLAINTS_SELECT, dateTimePickerFilterStart.Value, dateTimePickerFilterEnd.Value, FormPrintPreview.ReportTypes.Complaints) { MdiParent = MdiParent, WindowState = FormWindowState.Maximized };
            formPrintPreview.Show();
        }
        public void SetControlBox()
        {
            // Toolbar button
            mdiParent.toolStripMenuItemClear.Enabled = mdiParent.toolStripButtonClear.Enabled = true;
            mdiParent.toolStripMenuItemPrint.Enabled = mdiParent.toolStripButtonPrint.Enabled = !dataGridView.Rows.Count.Equals(0);
            EnableButtonSave();

            mdiParent.toolStripMenuItemModeI.Visible = true;
            mdiParent.toolStripMenuItemModeII.Visible = true;
            mdiParent.toolStripMenuItemModeIII.Visible = true;
            mdiParent.toolStripMenuItemModeI.Checked = true;

            // Status bar
            mdiParent.toolStripStatusLabelShowAllComplaints.Visible = mdiParent.toolStripStatusLabelNumberComplaintsFiltered.Visible = true;

            // Hooking up the binding source.
            mdiParent.toolStripMenu.BindingSource = sPCOMPLAINTSSELECTBindingSource;
        }
        public void ClearFilter()
        {
            // Reset each control
            dateTimePickerFilterStart.Checked = dateTimePickerFilterEnd.Checked = false;
            comboBoxDoctorFilter.SelectedIndex = -1;
            comboBoxOpenByUserFilter.SelectedIndex = -1;
            comboBoxCloseByUserFilter.SelectedIndex = -1;
            comboBoxDepartamentFilter.SelectedIndex = -1;
            comboBoxTypeOfComplaintFilter.SelectedIndex = -1;
            comboBoxTypeOfSampleFilter.SelectedIndex = -1;
            comboBoxRouteFilter.SelectedIndex = -1;

            // Call method
            RefreshComplaints();
        }
        public void ClearForm()
        {
            // Variables
            _complaintID = null;

            // Clear selection on Combo Boxes.
            comboBoxOpenByUserFilter.SelectedIndex = -1;
            comboBoxDoctor.SelectedIndex = -1;
            comboBoxCloseByUser.SelectedIndex = -1;
            comboBoxTypeOfSample.SelectedIndex = -1;
            dateTimePickerDate.Value = DateTime.Today;
            comboBoxDepartament.SelectedIndex = -1;
            comboBoxTypeOfComplaint.SelectedIndex = -1;

            // Set inserted and updated date
            labelInserted.Text = labelUpdated.Text = string.Empty;

            // Clear comments
            textBoxComments.Text = string.Empty;

            // Enable Controls
            EnabledControls(true);

            // Refresh Save Button
            EnableButtonSave();

            // Set focus
            buttonDoctor.Focus();
        }
        public void ChangeFormView(Global.FormViewModes mode)
        {
            switch (mode)
            {
                case Global.FormViewModes.ModeI:
                    splitContainer.Panel1Collapsed = false;
                    splitContainer.Panel2Collapsed = false;
                    break;
                case Global.FormViewModes.ModeII:
                    splitContainer.Panel1Collapsed = false;
                    splitContainer.Panel2Collapsed = true;
                    break;
                case Global.FormViewModes.ModeIII:
                    splitContainer.Panel1Collapsed = true;
                    splitContainer.Panel2Collapsed = false;
                    break;
            }
        }
        public void EnablePrintButton()
        {

        }
        public void Export()
        {
        }

        // General Purpose Functions
        private void EnabledControls(bool value)
        {
            // Setting comments and closing user
            labelOpenByUser.Enabled =
            comboBoxOpenByUser.Enabled =
            labelDoctor.Enabled =
            comboBoxDoctor.Enabled =
            buttonDoctor.Enabled =
            labelTypeOfSample.Enabled =
            comboBoxTypeOfSample.Enabled =
            dateTimePickerDate.Enabled =
            labelDepartament.Enabled =
            comboBoxDepartament.Enabled =
            labelTypeOfComplaint.Enabled =
            comboBoxTypeOfComplaint.Enabled =
            labelDateTime.Enabled =
            labelInserted.Enabled =
            labelUpdated.Enabled = value;
            labelComments.Enabled =
            textBoxComments.Enabled =
            comboBoxCloseByUser.Enabled = comboBoxCloseByUser.SelectedIndex.Equals(-1);
        }
        private void EnableButtonSave()
        {
            mdiParent.toolStripButtonSave.Enabled = mdiParent.toolStripMenuItemSave.Enabled  =
                !comboBoxOpenByUser.SelectedIndex.Equals(-1) &&
                !comboBoxDoctor.SelectedIndex.Equals(-1) &&
                !comboBoxTypeOfSample.SelectedIndex.Equals(-1) &&
                !comboBoxDepartament.SelectedIndex.Equals(-1) &&
                !comboBoxTypeOfComplaint.SelectedIndex.Equals(-1);
        }
        private void RefreshComplaints()
        {
            try
            {
                // Start process
                mdiParent.Begin();

                // Declare Local Variables
                DateTime? startDate, endDate;

                // Initializing Start and End Date variables.
                if (dateTimePickerFilterStart.Checked) startDate = dateTimePickerFilterStart.Value; else startDate = null;
                if (dateTimePickerFilterEnd.Checked) endDate = dateTimePickerFilterEnd.Value; else endDate = null;

                // Fill Table Adapter
                sP_COMPLAINTS_SELECTTableAdapter.Fill
                    (
                        dataSetSGLL.SP_COMPLAINTS_SELECT,
                        startDate,
                        endDate,
                        comboBoxRouteFilter.SelectedValue == null ? null : comboBoxRouteFilter.Text,
                        comboBoxDoctorFilter.SelectedValue == null ? null : comboBoxDoctorFilter.Text,
                        comboBoxOpenByUserFilter.SelectedValue == null ? null : comboBoxOpenByUserFilter.Text,
                        comboBoxCloseByUserFilter.SelectedValue == null ? null : comboBoxCloseByUserFilter.Text,
                        comboBoxDepartamentFilter.SelectedItem == null ? null : comboBoxDepartamentFilter.Text,
                        comboBoxTypeOfSampleFilter.SelectedValue == null ? null : comboBoxTypeOfSampleFilter.Text,
                        comboBoxTypeOfComplaintFilter.SelectedItem == null ? null : comboBoxTypeOfComplaintFilter.Text
                );

                // If more than one row was displayed on the grid then enable Print button.
                mdiParent.toolStripMenuItemPrint.Enabled = mdiParent.toolStripButtonPrint.Enabled = !dataGridView.Rows.Count.Equals(0);

                // Let the User Know, set up status bar
                mdiParent.toolStripStatusLabelNumberComplaintsFiltered.Text = string.Format(Resources.FilterStatusComplaints, dataGridView.Rows.Count, queriesTableAdapter.GetTotalComplaints());
                mdiParent.SetMessage(MDIParent.MessageType.Information, Resources.MessageSuccessfulComplaintsSearch);

                // Log File
            }
            catch (Exception exception)
            {
                // Report Error
                Utilities.ExceptionManager(exception);
            }
            finally
            {
                // End process
                mdiParent.End();
            }
        }
    }
}